program Project1;

{$APPTYPE CONSOLE}

uses
  Windows, Winsock;

const
  srvhost = '127.0.0.1';
  srvport = 606;
  remhost = '127.0.0.1';//'192.0.32.10';
  remport = 80;

  request1 = 'GET / HTTP/1.1'#10+
        'Accept: text/html, */*'#10+
        'Accept-Language: en'#10+
        'Accept-Encoding: gzip, deflate'#10+
        'User-Agent: Mozilla/10.0'#10+
        'Host: example.com'#10+
        'Connection: Keep-Alive'#10+
        'Pragma: no-cache'#10+
        'Accept-Language: en'#10#10;

type
  TSOCKS4_REQUEST = record
    ucVersion : byte;
    ucCommand : byte;
    wDestPort : word;
    dwDestIp  : dword;
  end;

var
  WD:TWSAData;
  S:TSocket;
  A:sockaddr_in;
  R:TSOCKS4_REQUEST;
  C:array [0..1024] of Char;
  
procedure die(obituary:string);
begin
  WriteLn(obituary);
  CloseSocket(S);
  WSACleanup;
  ReadLn(obituary);
  ExitProcess(0);
end;

procedure log(msg:string);
begin
  WriteLn(msg);
  //ReadLn(msg);
end;

begin
  WSAStartup($101, WD);
  log('---#startup');
  S:=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
  A.sin_family:=PF_INET;
  A.sin_port:=htons(srvport);
  A.sin_addr.S_addr:=inet_addr(srvhost);
  FillChar(A.sin_zero,sizeof(A.sin_zero),0);
  if connect(S,A,sizeof(A))<>0 then die('---##connect');
  log('---#connected');
  //Construct s4 header
  R.ucVersion:=4;
  R.ucCommand:=1;
  R.wDestPort:=htons(remport);
  R.dwDestIp:=inet_addr(remhost);
  //Send header to connect
  if send(S,R,sizeof(R),0)=0 then
    die('---##zero.s4hdr');
  //If not 90 then we give a shit, wtfk?
  recv(S,R,sizeof(R),0);
  if R.ucCommand<>90 then
    die('---##wtfk.s4con');

  //Transfers.. beginning of the end
  log('---#send1');
  lstrcpy(C,request1);
  log(C);
  if send(S,C,lstrlen(C),0)=0 then
    die('---##zero.send1');
  log('---#recv1');
  FillChar(C,sizeof(C),0);
  recv(S,C,sizeof(C),0);
  log(C);

  //Destruction completed
  die('---#session.end');
end.
